package spindles.gwt.server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import spindles.api.domain.Settings;
import spindles.api.domain.ThresholdGroup;
import spindles.api.services.SettingsService;
import spindles.api.util.Config;
import spindles.api.util.UserException;
import spindles.gwt.shared.GWTException;
import spindles.gwt.shared.SettingsDTO;
import spindles.gwt.shared.SettingsManager;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class SettingsServlet extends RemoteServiceServlet implements SettingsManager{
	
	transient final Logger log = LoggerFactory.getLogger(SettingsServlet.class);
	
	private SettingsService service = new SettingsService();
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -2255809590995626364L;

	@SuppressWarnings("unchecked")
	public SettingsDTO getSettings() {				
		
		Settings s = service.getSettings();
		log.info(s.toString());
		
		SettingsDTO dto = (SettingsDTO)ServletUtil.map(s, SettingsDTO.class);
		log.info(dto.toString());
		
		List<ThresholdGroup> threshholdGroups = ThresholdGroup.findAll();
		Map groups = new HashMap();		
		for(ThresholdGroup group : threshholdGroups){
			groups.put(group.getGroupName(), group.toString());
		}
		
		dto.setThresholdGroups(groups);
		
		return dto;
	}

	public void saveSettings(SettingsDTO dto) throws GWTException {		
		try {
			log.info(dto.toString());
			Settings s = (Settings)ServletUtil.map(dto, Settings.class);
			service.saveSettings(s);
			log.info(s.toString());
			
			Config.init(getServletContext().getRealPath("/WEB-INF/"));
		} catch (Exception e) {
			throw new GWTException(e);
		}		
	}
	
	public void detectSpindleIndications(String groupName) throws GWTException {
		try {
			if (ServletUtil.isImporting()) {
				throw new UserException("Cannot run this operation while importing data.");
			}
			ServletUtil.setImportStatus(true);
			
			service.detectSpindleIndications(groupName);
		} catch (Exception e) {
			throw new GWTException(e);
		} finally {
			ServletUtil.setImportStatus(false);
		}
		
	}
	
	

}
